package redis.event;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import redis.event.listener.KeyExpireListener;

import java.util.Map;


public class KeyExpireEventListener implements MessageListener, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String key = new String(message.getBody());
        Map<String, KeyExpireListener> listenerMap = this.applicationContext.getBeansOfType(KeyExpireListener.class);
        if (listenerMap != null && listenerMap.size() > 0) {
            for (KeyExpireListener listener : listenerMap.values()) {
                if (listener.suppportKey(key))
                    listener.action(key);
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
